package com.cuckoo.mall.test;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;

import com.orhanobut.logger.Logger;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class UploadService extends IntentService {
    public UploadService() {
        super("upload");
    }

    public static void startUpdateService(Context context, String tag, long time) {
        Intent intent = new Intent(context, UploadService.class);
        intent.putExtra("tag", tag);
        intent.putExtra("time", time);
        context.startService(intent);
    }


    @Override
    protected void onHandleIntent(@Nullable final Intent intent) {
        Observable.create(new ObservableOnSubscribe<String>() {

            @Override
            public void subscribe(ObservableEmitter<String> emitter) {
                Logger.d("所在的线程：", Thread.currentThread().getName());
                Logger.d("队列任务：" + intent.getStringExtra("tag") + "——————休眠" + intent.getLongExtra("time", 500));
                try {
                    Thread.sleep(intent.getLongExtra("time", 500));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                emitter.onNext(intent.getStringExtra("tag"));
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String s) {
                Logger.d("所在的线程2：", Thread.currentThread().getName());
                Logger.d("任务" + s + "结束");
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }
}
